"""
get radar data in the study area from 220 x 220 metrix
"""

# -*- coding: utf-8 -*-
import os
import pandas as pd


def list_dir(parent_path):
    """list files in dir path"""
    filepathes = []
    files = os.listdir(parent_path)
    for filename in files:
        f = os.path.join(parent_path, filename)
        if os.path.isfile(f):
            filepathes.append(f)
        elif os.path.isdir(f):
            filepathes.extend(list_dir(f))
    return filepathes


def get_radar(filepathes, out_dir):
    """get radar data from a list of file pathes"""
    for filepath in filepathes:
        filename = os.path.basename(filepath)
        out_file = os.path.join(out_dir, filename)
        df = pd.read_table(filepath, sep=" ", index_col=False, header=None)
        ext_radar = extract_radar(df)
        ext_radar.to_csv(out_file, index=False, header=False)


def extract_radar(radar_df):
    """extract radar data"""
    start_i = 55
    start_j = 95
    end_i = start_i + 90  # not included
    end_j = start_j + 90  # not included
    ext_radar = radar_df.iloc[start_i:end_i, start_j:end_j]
    return ext_radar


def main():
    """main function"""
    data_dir = r"F:/research/rainfall_estimation/dat/nimrod_output/2008/Output"
    out_dir = r"F:/research/rainfall_estimation/dat/nimrod_output/2008/90output"
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)
    filepathes = list_dir(data_dir)
    get_radar(filepathes, out_dir)


if __name__ == '__main__':
    print("get radar")
    main()
